// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
	let wxContext = cloud.getWXContext()
	let obj = {
		ToUserName: event.FromUserName,
		FromUserName: event.ToUserName,
		CreateTime: Date.parse(new Date()) / 1000,
		MsgType: 'text',
		Content: ''
	}
	await db.collection('test').add({
		data: {
			...wxContext,
			// ...event
		}
	})
	switch (event.MsgType) {
		case 'text':
			obj.Content =
				`Hi~感谢关注CRD克徕帝官方微信平台!\n<a class=\"miniapp-text-link\" data-miniprogram-appid=\"d3gzNTM1ZTgzN2ExMTk2N2E5\" data-miniprogram-path=\"cGFnZXMvc3RvcmUvZW50ZXJTdG9yZS5odG1s\" href=" ">一键预约</a >，前往CRD精品店，邂逅惊喜礼遇。欢迎进入<a class=\"miniapp-text-link\" data-miniprogram-appid=\"d3gzNTM1ZTgzN2ExMTk2N2E5\" data-miniprogram-path=\"cGFnZXMvc3BlY2lhbC9tZW1vcmlhbC5odG1s\" href=\"#\">专属定制</a > 服务，镌刻爱的独家印记。如需帮助，请致电400-102-0009(每日09:00-23:30)或后台回复【1】，我们将竭诚为您服务!`
			return obj
			break
		case 'event':
			if (event.Event == 'subscribe') {
				if (wxContext.FROM_UNIONID) {
					await db.collection('ws_user').where({
						unionid: wxContext.FROM_UNIONID
					}).update({
						data:{
							mpOpenid: wxContext.FROM_OPENID,
							updateTime: Date.now()
						}
					})
				}

				obj.Content = '已关注!'
				return obj
			}
			if (event.Event == 'unsubscribe') {
				await db.collection('ws_user').where({
					unionid: wxContext.FROM_UNIONID
				}).update({
					data:{
						mpOpenid: '',
						updateTime: Date.now()
					}
				})
			}
			break
	}


}
